﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace ErrorsParse
{
    static class Program
    {
        const string p = @"c:\Program Files (x86)\Windows Kits\8.1\Include\um\vdserr.h";
        const string id = "MessageId:", txt = "MessageText:";

        /// <summary>Read lines in the text file</summary>
        /// <param name="path"></param>
        /// <returns></returns>
        static IEnumerable<string> readLines( string path )
        {
            using( StreamReader sr = new StreamReader( p ) )
                while( !sr.EndOfStream )
                    yield return sr.ReadLine();
        }

        /// <summary>Split lines into the comments blocks</summary>
        /// <param name="lines"></param>
        /// <returns></returns>
        static IEnumerable<string[]> readCommentBlocks( this IEnumerable<string> lines )
        {
            List<string> list = new List<string>();

            foreach( string s in lines )
            {
                if( s.StartsWith( "//" ) )
                {
                    string t = s.Substring( 2 ).Trim();
                    if( !String.IsNullOrEmpty( t ) )
                        list.Add( t );
                    continue;
                }

                if( list.Count > 0 )
                {
                    yield return list.ToArray();
                    list.Clear();
                }
            }
            if( list.Count > 0 )
                yield return list.ToArray();
        }

        /// <summary>Parse a commants block into an error code and message</summary>
        /// <param name="cb"></param>
        /// <returns></returns>
        static Tuple<string, string> parseCommentBlocks( string[] cb )
        {
            if( cb.Length < 2 )
                return null;
            int ind = cb[ 0 ].IndexOf( id );
            if( ind < 0 )
                return null;
            string i = cb[ 0 ].Substring( ind + id.Length ).Trim();

            cb[ 0 ] = "";

            string all = String.Join( " ", cb ).Trim();
            ind = all.IndexOf( txt );
            if( ind < 0 )
                return null;
            all = all.Substring( ind + txt.Length ).TrimStart();
            return Tuple.Create( i, all ); ;
        }

        static void Main( string[] args )
        {
            foreach( var t in readLines( p )
                .readCommentBlocks()
                .Select( parseCommentBlocks )
                .Where( bb => null != bb ) )
            {
                Console.WriteLine( "		messages[ {0} ] = \"{1}\";",
                    t.Item1,
                    t.Item2.Replace( "\\", "\\\\" ) );
            }
        }
    }
}